package com.kiell.cubemall.product.service.impl;

import com.kiell.cubemall.common.utils.PageUtils;
import com.kiell.cubemall.common.utils.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;


import com.kiell.cubemall.product.dao.CategoryDao;
import com.kiell.cubemall.product.entity.CategoryEntity;
import com.kiell.cubemall.product.service.CategoryService;


@Service("categoryService")
public class CategoryServiceImpl extends ServiceImpl<CategoryDao, CategoryEntity> implements CategoryService {

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<CategoryEntity> page = this.page(
                new Query<CategoryEntity>().getPage(params),
                new QueryWrapper<CategoryEntity>()
        );

        return new PageUtils(page);
    }


    /**
     * @Author HuangZeWei
     * @Description //查询所有分类
     * @Date 16:24 2022/1/13
     * @Param
     * @return
     **/
    @Override
    public List<CategoryEntity> listWithTree() {
//        1.查询所有分类
        List<CategoryEntity> entities = baseMapper.selectList(null);
//        2.组装父子树形结构
//        2.1找到所有一级分类
        List<CategoryEntity> levelOneMenus = entities.stream().filter(
        //过滤一级分类aprentId = 0
         categoryEntity -> categoryEntity.getParentId() == 0
        ).map((menu) ->{
                //递归操作，关联子分类
                menu.setChildrens(getChildrens(menu,entities));
                return menu;
                }

        ).collect(Collectors.toList());

        return levelOneMenus;
    }


    /**
     * @Date 16:46 2022/1/14
     * @Param 批量删除
     * @return
     **/
    @Override
    public void removeMenusByIds(List<Integer> ids) {
        //TODO 检查菜单是否在其他地方引用
        //待增加检测
        //逻辑删除
        baseMapper.deleteBatchIds(ids);
    }

    /**
     * @Author HuangZeWei
     * @Description //递归查找指定分类的所有子类信息
     * @Date 16:40 2022/1/13
     * @Param
     * @return
     **/
    private List<CategoryEntity> getChildrens(CategoryEntity currentMenu, List<CategoryEntity> entities) {
        List<CategoryEntity> childrens = entities.stream().filter(
        //过滤出当前菜单的所有子分类
         categoryEntity -> currentMenu.getId().equals(categoryEntity.getParentId())
        ).map((menu) ->{
            //递归找到所有子分类
            menu.setChildrens(getChildrens(menu,entities));
            return menu;
        }
        ).collect(Collectors.toList());
        return childrens;
    }


}